package com.flute.framework.autoprompt;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class DefaultTokenWriter implements AutoPromptConstants, ITokenWriter {

	private BufferedWriter writer;
	private FileOutputStream stream;

	public DefaultTokenWriter(String fileName) {

		try {
			this.stream = new FileOutputStream(new File(fileName));
			this.writer = new BufferedWriter(new OutputStreamWriter(stream,
					"UTF8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public DefaultTokenWriter(String fileName, boolean append) {
		try {
			this.stream = new FileOutputStream(new File(fileName), append);
			this.writer = new BufferedWriter(new OutputStreamWriter(
					this.stream, "UTF8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void begineWrite() {
	}

	@Override
	public void endWrite() {
		try {
			this.writer.close();
			this.stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void writeToken(TokenData token) {
		try {
			writer.write(fromToken(token) + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String fromToken(TokenData token) {
		StringBuffer sb = new StringBuffer();
		sb.append(token.getText());
		sb.append(TOKEN_DATA_SPLITER);
		sb.append(token.getKey());
		sb.append(TOKEN_DATA_SPLITER);
		sb.append(token.getRecordOperator());
		sb.append(TOKEN_DATA_SPLITER);
		sb.append(token.getUpdatedate());
		for (int i = 0; i < token.getPriority().length; ++i) {
			sb.append(TOKEN_DATA_SPLITER);
			sb.append(token.getPriority()[i]);
		}
		return sb.toString().trim();
	}

	public void newLine() {
		try {
			this.writer.newLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
